function TFC1_CreateSets( subjects, requestedFrequencyBins, baselineSettings )
%TFC1_CREATESETS Main function to create sets of tfc data

global Database;

% Create a nice metadata structure for the frequencybins
frequencyBins = DescribeFrequencyBins(requestedFrequencyBins);

% Per subject
for sIdx = 1:length(subjects)
    subject = subjects{sIdx};
    
    data = []; % Start blank
    times = [];
    conds = {};
    
    filenames = GetSourceTimefrequencyFilenames(subject);
    for fIdx = 1:length(filenames)
        filename = filenames{fIdx};

        %% Get the data
        [bdata t s ch co] = TFC1a_LoadDataAndCalculateBins(filename, frequencyBins);
        if isempty(times); % Check to see whether all timescales are the same..
            times = t; 
        else
            if ~all(times==t); error('TFC1: Timescales between conditions and channels are not the same.'); end;
        end;
        [conditionname conditioncode conditiontype] = GetConditionByName(co);
        conds = [conds conditionname];

        %% Apply the baseline
        baselinedData = TFC1b_ApplyBaseline(bdata, times, conditiontype, baselineSettings);

        %% Create the datastructure that will end up in the file
        data.(s).(ch).(conditioncode).power = baselinedData; % data.SUBJECT.CHANNEL.CONDITIONCODE.power
        data.(s).(ch).(conditioncode).nrOfEpochs = size(baselinedData,3); % retrieving the nr of epochs from the actual data..
        disp(['Adding ' s '-' ch ': ' conditionname]);
    end
    conds = unique(conds); % Make sure every encountered condition is mentioned only once.
    
    % Write structure to file and add/update information in database
    filenameDestination = [Database.Path.TFCData subject '.tfcset']; 
    save(filenameDestination, 'data', 'frequencyBins', 'baselineSettings', 'times', '-v7.3');
    UpdateOrAddTFCFileInDatabase(filenameDestination, {subject}, conds, frequencyBins, baselineSettings, times);
    % Celebrate the succesfulness
    disp(['- Created ' filenameDestination]);

end

end

%% Helper functions

function frequencyBins = DescribeFrequencyBins(requested)
% Builds a generic description to identify the bands.

freqBands = {...
     4     7   'Theta'      '/theta'  ; ...
     7    13   'Alpha'      '/alpha'  ; ...
    13    30   'Beta'       '/beta'   ; ...
    30    70   'Low-Gamma'  'l/gamma' ; ...
    70   130   'High-Gamma' 'h/gamma' ; ...
    };

for i = 1:size(requested,1)
    frequencyBins(i).min = requested(i,1);
    frequencyBins(i).max = requested(i,2);
    frbnd = find([freqBands{:,1}] >= requested(i,1) & [freqBands{:,2}] <= requested(i,2));
    desc = '';
    texdesc = '';
    for j = 1:length(frbnd)
        if j>1, desc = [desc '/']; texdesc = [texdesc '']; end; % What is latex for / ??
        desc = [desc freqBands{frbnd(j),3}];
        texdesc = [texdesc freqBands{frbnd(j),4}];
    end
    frequencyBins(i).description = [desc ' (' num2str(requested(i,1)) '-' num2str(requested(i,2)) 'Hz)'];
    frequencyBins(i).texdescription = [texdesc ' (' num2str(requested(i,1)) '-' num2str(requested(i,2)) 'Hz)'];
end

end


function filenames = GetSourceTimefrequencyFilenames(subject)
%Select filenames for all timefrequency files for a given subject
global Database
cFilename = strcmp(Database.timefrequency_header, 'Filename');
cSubject = strcmp(Database.timefrequency_header, 'Subject');
% cChannel = strcmp(Database.timefrequency_header, 'Channel');
% cChannelType = strcmp(Database.timefrequency_header, 'ChannelType');
% cCondition = strcmp(Database.timefrequency_header, 'Condition');
% cFrequencies = strcmp(Database.timefrequency_header, 'Frequencies');
% cTimes = strcmp(Database.timefrequency_header, 'Times');

% Select the correct rows
tfSubject = strcmp(Database.timefrequency(:,cSubject), subject);
filenames = unique(Database.timefrequency(tfSubject, cFilename));
end